package com.eastdigit.system.service;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringServiceFactory implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public static <T> T getInstance(String beanName, Class<T> clazz) {
        try {
            T performer = applicationContext.getBean(beanName, clazz);
            if (performer == null) {
                throw new RuntimeException("没有找到[" + beanName + "]对应的执行程序!");
            }
            return performer;
        } catch (Exception e) {
            throw new RuntimeException("获取[" + beanName + "]对应的执行程序异常!");
        }
    }

    public static Object getBean(String name) throws BeansException {
        try {
            Object obj = applicationContext.getBean(name);
            if (obj == null) {
                throw new RuntimeException("没有找到[" + name + "]对应的bean!");
            }
            return obj;
        } catch (Exception e) {
            throw new RuntimeException("获取[" + name + "]对应的bean异常!");
        }
    } 
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        SpringServiceFactory.applicationContext = applicationContext;
    }
}
